package org.doubango.imsdroid.Login;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.doubango.imsdroid.R;
import org.doubango.imsdroid.Screens.BaseScreen;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.*;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static org.doubango.imsdroid.Login.LoginActivity.SIP_USERNAME;

/**
 * Created by TaZ on 2017/12/9.
 */

public class SoftBindActivity extends BaseScreen {

    private static enum METHOD_TYPE {
        GET_SOFTNUM,
        REQUEST_SOFTNUM,
    }

    private static String TAG = SoftBindActivity.class.getCanonicalName();
    private TextView json_soft;
    private final OkHttpClient client = new OkHttpClient();
    private String uid = SIP_USERNAME;
    private String json_back;
    private RadioGroup mRadioGroup;
    private RadioButton radioButton1;
    private RadioButton radioButton2;
    private RadioButton radioButton3;
    private RadioButton radioButton4;
    private RadioButton radioButton5;
    private Button another;
    private Button confirm;
    private String url;
    private List<String> SoftNumberArray = new ArrayList<String>();
    private static int index = 0;
    private String requestSoftNumber = "";

    private void updateSoftNumber() {
        radioButton1.setText(SoftNumberArray.get(index++ % SoftNumberArray.size()));
        radioButton2.setText(SoftNumberArray.get(index++ % SoftNumberArray.size()));
        radioButton3.setText(SoftNumberArray.get(index++ % SoftNumberArray.size()));
        radioButton4.setText(SoftNumberArray.get(index++ % SoftNumberArray.size()));
        radioButton5.setText(SoftNumberArray.get(index++ % SoftNumberArray.size()));
    }

    @SuppressWarnings("Handlerleak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String soft_pool = (String) msg.obj;
                Log.i("Response", soft_pool);
                parseJSONWithJSONObject(soft_pool);
                updateSoftNumber();
            } else {
                String response = (String) msg.obj;
                Log.i("RequestSoftNum", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    Log.i("SoftBindActivity", "response of request is" + response);
                    String remark = jsonObject.getString("remark");
                    String result = jsonObject.getString("result");
                    if(result.equals("true"))
                        Toast.makeText(SoftBindActivity.this, "号码"  + requestSoftNumber + "申请成功", Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(SoftBindActivity.this, remark, Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    protected SoftBindActivity() {
        super(SCREEN_TYPE.SOFTBIND_T, TAG);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.soft_bind);

        json_soft = (TextView) findViewById(R.id.txt_soft);
        mRadioGroup = (RadioGroup) findViewById(R.id.softNumPool);
        radioButton1 = (RadioButton) findViewById(R.id.list_1);
        radioButton2 = (RadioButton) findViewById(R.id.list_2);
        radioButton3 = (RadioButton) findViewById(R.id.list_3);
        radioButton4 = (RadioButton) findViewById(R.id.list_4);
        radioButton5 = (RadioButton) findViewById(R.id.list_5);
        another = (Button) findViewById(R.id.another);
        confirm = (Button) findViewById(R.id.confirm);
        postRequest(METHOD_TYPE.GET_SOFTNUM);

        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Log.i("Choose", "" + ((RadioButton) findViewById(i)).getText());
                requestSoftNumber = (String) ((RadioButton) findViewById(i)).getText();
            }
        });

        another.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("SoftBindActivity", "Soft number updated");
                updateSoftNumber();
            }
        });

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                postRequest(METHOD_TYPE.REQUEST_SOFTNUM);
            }
        });
    }

    private void postRequest(final METHOD_TYPE methodType) {

        //建立请求表单，添加上传服务器的参数
        RequestBody formBody;

        if (methodType.equals(METHOD_TYPE.GET_SOFTNUM)) {
            url = "http://59.110.217.175:8080/b/findSoftNums.action";
            formBody = new FormBody.Builder()
                    .build();
        } else {
            url = "http://59.110.217.175:8080/b/createSoftNums.action?";
            formBody = new FormBody.Builder()
                    .add("userId", uid)
                    .add("softNo", requestSoftNumber)
                    .build();
        }


        //发起请求
        final Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    String responseData = response.body().string();

                    if (response.isSuccessful()) {
                        if (methodType.equals(METHOD_TYPE.GET_SOFTNUM))
                            mHandler.obtainMessage(1, responseData).sendToTarget();
                        else
                            mHandler.obtainMessage(2, responseData).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

//    {"numbers":[
//        {"isSoft":"0","softNumber":"15612311234"},{"isSoft":"0","softNumber":"15617341234"},
//        {"isSoft":"0","softNumber":"15618341234"},{"isSoft":"0","softNumber":"15616341234"},
//        {"isSoft":"0","softNumber":"15312341234"},{"isSoft":"0","softNumber":"15412341234"},
//        {"isSoft":"0","softNumber":"15512341234"},{"isSoft":"0","softNumber":"15112341234"},
//        {"isSoft":"0","softNumber":"15613341234"},{"isSoft":"0","softNumber":"15614341234"},
//        {"isSoft":"0","softNumber":"15615341234"},{"isSoft":"0","softNumber":"15610341234"},
//        {"isSoft":"0","softNumber":"15619341234"}]}

    private void parseJSONWithJSONObject(String jsonData) {
        try {

            JSONObject jsonObject = new JSONObject(jsonData);
            String jsonArray = jsonObject.getString("numbers");
            JSONArray jsonArrayNumber = new JSONArray(jsonArray);

            for (int i = 0; i < jsonArrayNumber.length(); i++) {

                JSONObject jsonSoftObject = jsonArrayNumber.getJSONObject(i);
                String isSoft = jsonSoftObject.getString("isSoft");
                String softNumber = jsonSoftObject.getString("softNumber");

                if (isSoft.equals("0")) {
                    SoftNumberArray.add(softNumber);

                } else {
                    return;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
